package com.kunminx.architecture.utils;

import com.kunminx.architecture.ResourceTable;
import com.kunminx.architecture.utils.TextUtils;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.app.AbilityContext;
import ohos.app.Context;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;
import org.jetbrains.annotations.NonNls;

/**
 * @author KunMinX
 * Create at 2018/7/6
 */
public class PermissionUtils {

    private static final int REQUEST_PERMISSIONS = 0x0001;

    public static void requestPermissionInAbility(IPermissionCallback iPermissionCallback, AbilityContext abilityContext, String... permissions) {
        sIPermissionCallback = iPermissionCallback;
        boolean allAllowed = true;
        for (String permission : permissions) {
            if (needPermission(abilityContext, permission)) {
                abilityContext.requestPermissionsFromUser(new String[]{permission}, REQUEST_PERMISSIONS);
                allAllowed = false;
            }
        }
        if (allAllowed) {
            sIPermissionCallback.onResult(null);
        }
    }

    public static void requestPermissionInFraction(IPermissionCallback iPermissionCallback, Fraction fraction, String... permissions) {
        sIPermissionCallback = iPermissionCallback;
        for (String permission : permissions) {
            if (needPermission(fraction.getFractionAbility(), permission)) {
                fraction.requestPermissionsFromUser(new String[]{permission}, REQUEST_PERMISSIONS);
            }
        }
    }

    public static boolean needPermission(Context context, String permission) {
        return context.verifySelfPermission(permission) != IBundleManager.PERMISSION_GRANTED;
    }

    public static void onRequestPermissionsResult(Context context, int requestCode, @NonNls String[] permissions, @NonNls int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSIONS:
                StringBuilder sb = new StringBuilder();
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != IBundleManager.PERMISSION_GRANTED) {
                            sb.append(getGroupNameByPermissionName(context, permissions[i])).append(",");
                        }
                    }
                    String str = sb.toString();
                    if (str.contains(",") && str.endsWith(",")) {
                        sb.deleteCharAt(sb.length() - 1);
                    }
                }
                if (TextUtils.isEmpty(sb.toString())) {
                    if (sIPermissionCallback != null) {
                        sIPermissionCallback.onResult(null);
                    }
                } else {
                    if (sIPermissionCallback != null) {
                        sIPermissionCallback.onResult(sb.toString());
                    }
                }
                break;
            default:
        }
    }

    private static IPermissionCallback sIPermissionCallback;


    /**
     * get group name by danger private permission
     *
     * @param context
     * @param permissionName
     * @return String
     */
    public static String getGroupNameByPermissionName(Context context, String permissionName) {
        String groupName = "";
        switch (permissionName) {
            //by public permission
            case SystemPermission.READ_HEALTH_DATA: //不确定
                groupName = context.getString(ResourceTable.String_permission_group_sensor);
                break;
            case SystemPermission.LOCATION:
                groupName = context.getString(ResourceTable.String_permission_group_location);
                break;
            case SystemPermission.CAMERA:
                groupName = context.getString(ResourceTable.String_permission_group_camera);
                break;
            // case Manifest.permission.RECORD_AUDIO:
            case SystemPermission.MICROPHONE: //不确定
                groupName = context.getString(ResourceTable.String_permission_group_audio);
                break;

            //by private permission
            case SystemPermission.GET_TELEPHONY_STATE:
            case SystemPermission.PLACE_CALL:
            case SystemPermission.READ_CALL_LOG:
            case SystemPermission.WRITE_CALL_LOG:
            case SystemPermission.MANAGE_VOICEMAIL:
            // case Manifest.permission.USE_SIP: // TODO 未提供：允许程序使用SIP视频服务
            // case Manifest.permission.PROCESS_OUTGOING_CALLS: //TODO 未提供：允许程序监视，修改或放弃播出电话
                groupName = context.getString(ResourceTable.String_permission_group_phone);
                break;
            case SystemPermission.SEND_MESSAGES:
            case SystemPermission.RECEIVE_SMS:
            case SystemPermission.READ_MESSAGES:
            case SystemPermission.RECEIVE_WAP_MESSAGES:
            case SystemPermission.RECEIVE_MMS:
                groupName = context.getString(ResourceTable.String_permission_group_sms);
                break;
            case SystemPermission.READ_CONTACTS:
            case SystemPermission.WRITE_CONTACTS:
            case SystemPermission.MANAGE_LOCAL_ACCOUNTS:
                groupName = context.getString(ResourceTable.String_permission_group_contact);
                break;
            case SystemPermission.READ_CALENDAR:
            case SystemPermission.WRITE_CALENDAR:
                groupName = context.getString(ResourceTable.String_permission_group_calendar);
                break;
            case SystemPermission.WRITE_USER_STORAGE:
            case SystemPermission.READ_USER_STORAGE:
                 groupName = context.getString(ResourceTable.String_permission_group_extenal_storage);
                 break;
            default:
        }
        return groupName;
    }

    public interface IPermissionCallback {
        /**
         * if msg not null, means permission denied
         *
         * @param msg
         */
        void onResult(String msg);
    }

}
